import { useUserStore } from '@/stores/use_user_store'
import { useRouterStore } from '@/stores/use_router_store'
import { LoadingBar, Loading } from "quasar"


import getPageTitle from '@/utils/page'
import router from '@/router'
// import Nprogress from 'nprogress'
// import 'nprogress/nprogress.css'
import * as util from '@/utils';
// Nprogress.configure({ showSpinner: false, ease: 'ease', speed: 500 })

const whiteList = ['Login', 'Init']

const getRouter = async (userStore) => {
  const routerStore = useRouterStore()
  await routerStore.SetAsyncRouter()
  await userStore.GetUserInfo()
  const asyncRouters = routerStore.asyncRouters
  asyncRouters.forEach(asyncRouter => {
    router.addRoute(asyncRouter)
  })
}

let loadingCount = 0; // 计数器跟踪加载次数
function startLoading() {
  loadingCount++;
  // 只有第一次调用时才真正显示
  // console.log(`loadingCount 👉`,loadingCount)
  if (loadingCount === 1) {
    Loading.show();
    LoadingBar.start();
  }
}

function stopLoading() {
    Loading.hide();
    LoadingBar.stop();
}

async function handleKeepAlive(to) {
  if (to.matched.some(item => item.meta.keepAlive)) {
    // console.log(`处理 handleKeepAlive to👉`, to)
    if (to.matched && to.matched.length > 2) {
      for (let i = 1; i < to.matched.length; i++) {
        // 删除中间层路由，因为router缓存只支持两层
        const element = to.matched[i - 1]
        if (element.name === 'layout') {
          to.matched.splice(i, 1)
          await handleKeepAlive(to)
        }
        // 等待按需加载的组件加载完成
        // 因为只有组件加载完成后，才能准确地判断是否需要对其进行缓存操作。
        if (typeof element.components.default === 'function') {
          await element.components.default()
          await handleKeepAlive(to)
        }
      }
    }
  }
}

router.beforeEach(async (to, from) => {
  // console.log(`to 👉`, to)
  // console.log(`to.matched.length 👉`, to.matched.length)
  // console.log(`from 👉`,from)
  const routerStore = useRouterStore()
  // Nprogress.start()
  startLoading()

  const userStore = useUserStore()
  to.meta.matched = [...to.matched]
  handleKeepAlive(to)

  const token = userStore.token
  // 在白名单中的判断情况
  document.title = getPageTitle(to.meta.title, to)
  if (to.meta.client) {
    return true
  }
  if (whiteList.indexOf(to.name) > -1) {
    // console.log(`在白名单中 to 👉`,to)
    if (token) {
      if (!routerStore.取动态路由计数 && whiteList.indexOf(from.name) < 0) {
        await getRouter(userStore)
      }
      // token 可以解析但是却是不存在的用户 id 或角色 id 会导致无限调用
      if (userStore.userInfo?.authority?.defaultRouter != null) {
        // const routes=router.getRoutes()
        // console.log(`routes 👉`,routes)
        // console.log(`userStore.主页路由 👉`, userStore.主页路由)
        // if (router.hasRoute(userStore.主页路由)) {
        //   return { name: userStore.主页路由 }
        return userStore.主页路由
        // } else {
        //   return { path: '/layout/404' }
        // }
      } else {
        // 强制退出账号
        userStore.ClearStorage()
        return {
          name: 'Login',
          query: {
            redirect: document.location.hash
          }
        }
      }
    } else {
      stopLoading()
      return true
    }
  } else {
    // 不在白名单中并且已经登录的时候
    // console.log(`不在白名单中并且已经登录的时候 ing👇`)
    if (token) {
      if (sessionStorage.getItem("needToHome") === 'true') {
        sessionStorage.removeItem("needToHome")
        stopLoading()
        return { path: '/' }
      }
      // 添加flag防止多次获取动态路由和栈溢出
      if (!routerStore.取动态路由计数 && whiteList.indexOf(from.name) < 0) {
        await getRouter(userStore)
        if (userStore.token) {
          return { ...to, replace: true }
          // if (router.hasRoute(userStore.主页路由)) {
          //   return { ...to, replace: true }
          // } else {
          //   return { path: '/layout/404' }
          // }
        } else {
          return {
            name: 'Login',
            query: { redirect: to.href }
          }
        }
      } else {
        if (to.matched.length) {
          stopLoading()
          return true
        } else {
          return { path: '/layout/404' }
        }
      }
    }
    // 不在白名单中并且未登录的时候
    if (!token) {
      return {
        name: 'Login',
        query: {
          redirect: document.location.hash
        }
      }
    }
  }
})


router.afterEach(() => {
  // 路由加载完成后关闭进度条
  // document.getElementsByClassName('main-cont main-right')[0]?.scrollTo(0, 0)
  // Nprogress.done()
  stopLoading()
})

router.onError(() => {
  // 路由发生错误后销毁进度条
  // Nprogress.remove()
  stopLoading()
})

stopLoading()
